<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>树形结构转化扁平的数据结构</title>
  </head>
  <body>
    <script>
      let tree = [
        {
          id: 1,
          name: "部门1",
          pid: 0,
          children: [
            {
              id: 2,
              name: "部门2",
              pid: 1,
              children: [],
            },
            {
              id: 3,
              name: "部门3",
              pid: 1,
              children: [
                {
                  id: 4,
                  name: "部门4",
                  pid: 3,
                  children: [
                    {
                      id: 5,
                      name: "部门5",
                      pid: 4,
                    },
                  ],
                },
              ],
            },
          ],
        },
      ];

      const getData = (data) => {
        let resultData = []; //保存最终的结果
        const treeToArray = (data, result) => {
          data.forEach((item) => {
            if (!item.children || item.children.length === 0) {
              result = [
                ...result,
                { id: item.id, name: item.name, pid: item.pid },
              ];
              resultData = result;
            } else {
              treeToArray(item.children, [
                ...result,
                { id: item.id, name: item.name, pid: item.pid },
              ]);
            }
          });
        };
        treeToArray(data,[])
        return resultData
      };
      console.log(getData(tree));
    </script>
  </body>
</html>
